package com.guomei.controller;

import com.guomei.bean.*;
import com.guomei.bean.user.dto.BindDistributorIdDTO;
import com.guomei.configs.WechatMpConfig;
import com.guomei.constans.ResultCode;
import com.guomei.service.UserService;
import com.guomei.utils.JwtUtil;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private WechatMpConfig wechatMpConfig;
    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<?> register(@Valid @RequestBody RegisterDTO registerDTO, BindingResult result) {
        log.info("用户注册入参：{}", registerDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.register(registerDTO);
    }

    /**
     * 密码登录
     */
    @PostMapping("/login/password")
    public Result<?> loginByPassword(@Valid @RequestBody LoginDTO loginDTO,BindingResult result) {
        log.info("密码登录入参：{}", loginDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        if (loginDTO.getPassword() == null){
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "密码不能为空");
        }
        return userService.loginByPassword(loginDTO);
    }

    /**
     * 验证码登录
     */
    @PostMapping("/login/code")
    public Result<?> loginByCode(@Valid @RequestBody LoginDTO loginDTO,BindingResult result) {
        log.info("验证码登录入参：{}", loginDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.loginByCode(loginDTO);
    }
    /**
     * 生成登录二维码
     */
    @GetMapping("/login/qrcode")
    public Result<?> generateLoginQrCode(@RequestParam(required = false) Integer userId) {
        try {
            // 生成唯一的场景ID
            Integer sceneId = Math.abs(UUID.randomUUID().toString().hashCode()) % 1000000000; // 生成9位数字场景ID

            return userService.generateTempQrCode(sceneId, userId);
        } catch (Exception e) {
            log.error("生成微信登录二维码失败", e);
            return Result.error("生成二维码失败: " + e.getMessage());
        }
    }

    /**
     * 检查二维码扫描状态
     */
    @GetMapping("/login/qrcode/status")
    public Result<?> checkQrCodeStatus(@RequestParam String qrCodeId) {
        try {
            // log.info("检查二维码扫描状态: qrCodeId={}", qrCodeId);
            return userService.checkQrCodeScanStatus(qrCodeId);
        } catch (Exception e) {
            log.error("检查二维码状态失败", e);
            return Result.error("检查状态失败: " + e.getMessage());
        }
    }

    /**
     * 分销码绑定功能
     */
    @PostMapping("/bind/bindDistributor")
    public Result<?> bindDistributorId(@RequestBody BindDistributorIdDTO bindDistributorIdDTO) {
        return userService.bindDistributorId(bindDistributorIdDTO);
    }


    /**
     * 微信公众号服务器验证（GET请求）
     */
    @GetMapping("/wxmp/server")
    public String wechatVerify(@RequestParam String signature,
                               @RequestParam String timestamp,
                               @RequestParam String nonce,
                               @RequestParam String echostr) {
        try {
            log.info("微信服务器验证请求，signature: {}, timestamp: {}, nonce: {}, echostr: {}", 
                    signature, timestamp, nonce, echostr);

            // 验证签名
            boolean isValid = userService.verifyWechatSignature(signature, timestamp, nonce);
            
            if (isValid) {
                log.info("微信服务器验证成功");
                return echostr;
            } else {
                log.warn("微信服务器验证失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("微信服务器验证异常", e);
            return "error";
        }
    }

    /**
     * 微信公众号消息推送回调接口（POST请求）
     */
    @PostMapping("/wxmp/server")
    public Object wechatCallback(@RequestParam String signature,
                                @RequestParam String timestamp,
                                @RequestParam String nonce,
                                @RequestParam(required = false) String msg_signature,
                                @RequestParam(required = false) String encrypt_type,
                                @RequestBody String requestBody,
                                HttpServletResponse response) {
        try {
            log.info("微信消息推送回调，signature: {}, timestamp: {}, nonce: {}, msg_signature: {}, encrypt_type: {}", 
                    signature, timestamp, nonce, msg_signature, encrypt_type);
            log.info("请求体: {}", requestBody);

            // 处理微信消息
            Object result = userService.handleWechatMessage(signature, timestamp, nonce, msg_signature, encrypt_type, requestBody);
            
            if (result != null) {
                // 如果是加密模式，设置返回内容类型
                if ("aes".equals(encrypt_type)) {
                    response.setContentType("application/json;charset=UTF-8");
                } else {
                    response.setContentType("text/plain;charset=UTF-8");
                }
                return result;
            } else {
                return "success";
            }
        } catch (Exception e) {
            log.error("微信消息推送处理失败", e);
            return "fail";
        }
    }


    /**
     * 微信登录
     */
    @PostMapping("/login/wechat")
    public Result<?> loginByWechat(@Valid @RequestBody WechatLoginDTO wechatLoginDTO, BindingResult result) {
        log.info("微信登录入参：{}", wechatLoginDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            // 通过code获取用户信息
            WechatUserInfo userInfo = userService.getUserInfoByCode(wechatLoginDTO.getCode());

            if (userInfo == null) {
                return Result.error("获取微信用户信息失败");
            }

            // 例如：查询用户是否存在，不存在则自动注册，然后生成JWT token等

            return userService.autoRegister(userInfo);
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 微信扫码登录（自动创建用户）
     */
    @PostMapping("/login/qrcode/scan")
    public Result<?> loginByQrCodeScan(@RequestParam String openid) {
        log.info("微信扫码登录：openid={}", openid);
        try {
            if (openid == null || openid.trim().isEmpty()) {
                return Result.error("OpenID不能为空");
            }
            
            return userService.autoCreateUserByQrScan(openid.trim());
        } catch (Exception e) {
            log.error("微信扫码登录失败", e);
            return Result.error("扫码登录失败: " + e.getMessage());
        }
    }


    /**
     * 获取当前用户信息（包含角色信息）
     */
    @GetMapping("/current-user")
    public Result<?> getCurrentUser(HttpServletRequest request) {
        try {
            // 从request属性中获取用户信息（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");

            // 检查用户ID是否存在
            if (userId == null) {
                return Result.error("无法获取用户信息");
            }

            return userService.getUserInfoWithRoles(userId);
        } catch (Exception e) {
            log.error("获取用户信息异常: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String authHeader = request.getHeader("Authorization");

            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                // 提取token
                String token = authHeader.substring(7);

                // 从Redis中删除token
                JwtUtil.removeToken(token);

                log.info("用户退出登录，token已清除");
            }

            return Result.success("退出登录成功");
        } catch (Exception e) {
            log.error("退出登录异常: {}", e.getMessage(), e);
            return Result.success("退出登录成功"); // 即使删除失败也返回成功，因为客户端会清除token
        }
    }

    @PostMapping("/changePassword")
    public Result<?> changePassword(@Valid @RequestBody ChangePassword changePassword, BindingResult result) {
        log.info("修改密码入参：{}", changePassword);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.changePassword(changePassword);
    }

    @PostMapping("/getALLUser")
    public Result<?> getALLUser(@Valid @RequestBody GetAllUserDTO getAllUserDTO, BindingResult result) {
        log.info("获取所有未授权用户入参：{}", getAllUserDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.getALLUser(getAllUserDTO);
    }

    @PostMapping("/getALLTeacher")
    public Result<?> getALLTeacher(@Valid @RequestBody GetAllUserDTO getAllUserDTO, BindingResult result) {
        log.info("获取所有老师入参：{}", getAllUserDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.getALLTeacher(getAllUserDTO);
    }


    @PostMapping("/deleteRole")
    public Result<?> deleteRole(@Valid @RequestBody DeleteRoleDTO deleteRoleDTO, BindingResult result) {
        log.info("删除角色入参：{}", deleteRoleDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.deleteRole(deleteRoleDTO);
    }

    @PostMapping("/updateUser")
    public Result<?> updateUser(@Valid @RequestBody UpdateUser updateUser, BindingResult result) {
        log.info("修改个人信息：{}", updateUser);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        return userService.updateUser(updateUser);
    }
    
    /**
     * 同步用户角色（支持添加和删除角色）
     * @param userRoles 期望的最终角色列表
     * @param userId 用户ID
     * @return 同步结果
     */
    @PostMapping("/assignRoleToUser/{userId}")
    public Result<?> assignRoleToUser(@RequestBody List<UserRole> userRoles, @PathVariable Long userId){
        log.info("同步用户角色入参：用户ID={}, 角色列表={}", userId, userRoles);
        return userService.assignRoleToUser(userRoles, userId);
    }
}
